package com.kotodama.application.services;

import com.kotodama.domain.entities.User;
import com.kotodama.domain.repositories.UserRepository;
import com.kotodama.infrastructure.tenant.context.TenantContext;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    
    public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }
    
    public boolean existsByUsername(String username) {
        String tenantId = TenantContext.getTenantId();
        return userRepository.findByTenantIdAndUsername(tenantId, username).isPresent();
    }
    
    @Transactional
    public User register(User user) {
        // 确保设置了租户ID
        if (user.getTenantId() == null || user.getTenantId().isEmpty()) {
            user.setTenantId(TenantContext.getTenantId());
        }
        
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        
        return userRepository.save(user);
    }
}
